//
//  QInfoManageVC.m
//  QoilPublic
//
//  Created by 杨凯 on 2017/2/17.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "QInfoManageVC.h"
#import "QInfoManageCell.h"
#import "QAddCommonVC.h"
#import "QAddSpecialVC.h"
#import "QCommonStateVC.h"
#import "QInvoiceInfoModel.h"
#import "QInvoiceListModel.h"
#import "QMakeInvoiceVC.h"
#import "QAddSpecialVC.h"
#import "QShowChooseView.h"
@interface QInfoManageVC ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger _index;
    NSMutableArray *_dataArr;

}
@property (nonatomic,strong)UITableView *tbView;
@end

@implementation QInfoManageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"开票信息管理";
    [self createUI];
    [self requestData];
    _dataArr = [NSMutableArray array];
    

    WS(wSelf);
    _tbView.mj_header = [QViewUtility showHeadRefresh:^{
        [_tbView.mj_footer resetNoMoreData];
        [wSelf requestData];
    }];
    _tbView.mj_footer = [QViewUtility showFootRefresh:^{
        [wSelf requestMoreData];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTab) name:kNotificationAddInvoiceSuccess object:nil];

    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationAddInvoiceSuccess object:nil];
}
#pragma marks ---添加发票成功
- (void)refreshTab{

    [_dataArr removeAllObjects];
    [self requestData];
}
- (void)requestData{
    _index = 1;
    NSString *start = [NSString stringWithFormat:@"%ld",(long)_index];
    NSString *url = [QParamService urlWithAction:@"findInvoiceList"];
    NSDictionary *para= [QParamService findInvoiceListWithState:self.state Start:start pageSize:KpageSize];
    [QViewUtility showMBHudToView:self.view hideBg:YES];
    [QViewUtility dismissNoDataViewInVC:self];
    [QViewUtility disMissNoNetWorkInVC:self];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [_tbView.mj_header endRefreshing];
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [_dataArr removeAllObjects];
            QInvoiceInfoModel *model =[QInvoiceInfoModel objectFromDict:basModel.items];
            [_dataArr addObjectsFromArray:model.list];
            
            if(_dataArr.count == 0){
                [QViewUtility showNoDataViewInView:_tbView string:@""];
            }else{
                if(model.list.count < 10){
                    [_tbView.mj_footer noticeNoMoreData];
                }
            }
            [_tbView reloadData];

        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}


- (void)requestMoreData{
    _index++;
    NSString *start = [NSString stringWithFormat:@"%ld",(long)_index];
    NSString *url = [QParamService urlWithAction:@"findInvoiceList"];
    NSDictionary *para= [QParamService findInvoiceListWithState:self.state Start:start pageSize:KpageSize];
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [_tbView.mj_footer endRefreshing];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        
        if([basModel.result isEqualToString:@"success"]){
            QInvoiceInfoModel *model = [QInvoiceInfoModel objectFromDict:basModel.items];
            [_dataArr addObjectsFromArray:model.list];
            if(model.list.count < 10){
                [_tbView.mj_footer noticeNothing];
                //[QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"没有更多了" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            }
            [_tbView reloadData];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];

}
- (void)createUI{
    [self.view addSubview:self.tbView];
    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.bottom.equalTo(@0);
    }];
    [self.tbView registerNib:[UINib nibWithNibName:@"QInfoManageCell" bundle:nil] forCellReuseIdentifier:@"QInfoManageCell"];
    UIButton *navButton = [UIButton buttonWithType:UIButtonTypeCustom];
    navButton.frame = CGRectMake(0,0,55, 45);
    //navButton.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    navButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [navButton setTitle:@"添加" forState:UIControlStateNormal];
    [navButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [navButton addTarget:self action:@selector(addInvoiceAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:navButton];
    self.navigationItem.rightBarButtonItem = rightItem;

}
- (void)addInvoiceAction{
    //添加发票
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"普票", @"专票", nil];
    
    [actionSheet showInView:self.view];


}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    QAddSpecialVC * vc =[[QAddSpecialVC alloc]init];

    if (buttonIndex == 0) {
        CLog(@"普票");
        vc.url = @"addMajorInvoice.html";
        [self.navigationController pushViewController:vc animated:YES];
    } else if (buttonIndex == 1) {
        CLog(@"专票");
        vc.url = @"addInvoice.html";
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 8;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QInfoManageCell * cell= [tableView dequeueReusableCellWithIdentifier:@"QInfoManageCell" forIndexPath:indexPath];
    //WS(wSelf);
    __weak QInfoManageVC *wSelf = self;

    QInvoiceListModel *model =_dataArr[indexPath.section];

    cell.model = model;
    cell.ChangeBlock = ^(NSInteger tag){
        CLog(@"%ld",(long)tag);
        __strong QInfoManageVC *sSelf = wSelf;

        if (tag == 1) {// 跳转编辑页面
            if ([model.invoiceType isEqualToString:@"2"]) {
                QAddSpecialVC * vc1 =[[QAddSpecialVC alloc]init];
                vc1.state = model.state;
                vc1.credentialsId = model.credentialsId;
                [wSelf.navigationController pushViewController:vc1 animated:YES];
            }
            
        }else{
            // 删除订单
            [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"确定删除发票?" leftTitle:@"取消" rightTitle:@"确定" type:1 myBlock:^(NSInteger tag1) {
                if(tag1 == 1){
                    __strong QInfoManageVC *ssSelf = sSelf;

                    [ssSelf deletInvoiceDetail:indexPath];

                }
            }];
            


        }
    };
    return cell;
}

#pragma mark ---删除发票
- (void)deletInvoiceDetail:(NSIndexPath *)indexPath{
    
    NSString *url =[QParamService urlWithAction:@"deletInvoiceDetail"];
    QInvoiceListModel *model =_dataArr[indexPath.section];
    NSDictionary *param =[QParamService deletInvoiceDetailWithCredentialsId:model.credentialsId];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:_tbView];
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        
        if([basModel.result isEqualToString:@"success"]){
            [_dataArr removeObjectAtIndex:indexPath.section];
            
            [_tbView reloadData];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.popToWhere isEqualToString:@"QMakeInvoiceVC"]) {
        
        QInvoiceListModel *model =_dataArr[indexPath.section];
        self.InformationBlock(model);
        [self.navigationController popViewControllerAnimated:YES];

    }else{
        QAddSpecialVC * vc1 =[[QAddSpecialVC alloc]init];

        //QCommonStateVC * vc =[[QCommonStateVC alloc]init];
        QInvoiceListModel *model =_dataArr[indexPath.section];
        if ([model.invoiceType isEqualToString:@"1"]) {
            vc1.credentialsId = model.credentialsId;
            vc1.state = model.state;//普票
            vc1.url = @"lookMajorInvoice.html";
            [self.navigationController pushViewController:vc1 animated:YES];
        }else{
            vc1.state = model.state;
            vc1.credentialsId = model.credentialsId;
            vc1.url = @"lookInvoice.html";

            [self.navigationController pushViewController:vc1 animated:YES];

        }

    }
}

- (UITableView*)tbView {
    if (!_tbView) {
        _tbView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tbView.dataSource = self;
        _tbView.delegate = self;
        _tbView.backgroundColor = [UIColor clearColor];
        _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tbView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
